<template>
  <div class="app-container">
    <!-- 顶部标题 -->
    <div class="header">
      <div class="title">
        <i class="fas fa-utensils"></i>
        <h1>长虹乡餐饮欢迎您</h1>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card shadow="hover" class="search-card">
      <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          class="search-form"
      >
        <div class="form-grid">
          <el-form-item label="餐饮名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable />
          </el-form-item>

          <el-form-item label="单价" prop="price">
            <el-input v-model="queryParams.price" placeholder="请输入价格" clearable />
          </el-form-item>

          <el-form-item label="分类" prop="category">
            <el-input v-model="queryParams.category" placeholder="请输入分类" clearable />
          </el-form-item>

          <el-form-item label="份量" prop="portionSize">
            <el-input v-model="queryParams.portionSize" placeholder="请输入份量" clearable />
          </el-form-item>

          <div class="form-actions">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <!-- <el-card shadow="hover" class="toolbar-card">
      <div class="toolbar">
        <el-button type="warning" plain icon="el-icon-download" @click="handleExport" v-hasPermi="['system:food:export']">
          导出
        </el-button>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" class="right-toolbar" />
      </div>
    </el-card> -->

    <!-- 卡片区域 -->
    <div v-loading="loading" class="cards-container">
      <div
          v-for="food in foodList"
          :key="food.id"
          class="food-card"
          :class="{ 'card-selected': isSelected(food.id) }"
      >
        <!-- 图片区域 -->
        <div class="card-image">
          <image-preview :src="food.imageUrl" :width="400" :height="300" class="food-image" />
          <div class="card-selector">
            <el-checkbox v-model="selectedFoods" :label="food.id" class="selection-checkbox" />
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="card-content">
          <div class="card-header">
            <h3 class="food-name">{{ food.name }}</h3>
            <span class="food-category">{{ food.category || '未分类' }}</span>
          </div>

          <div class="food-stats">
            <div class="stat-item">
              <div class="stat-icon">
                <i class="fas fa-tag"></i>
              </div>
              <div class="stat-label">价格</div>
              <div class="stat-value">{{ food.price || '0' }} 元</div>
            </div>

            <div class="stat-item">
              <div class="stat-icon">
                <i class="fas fa-weight"></i>
              </div>
              <div class="stat-label">份量</div>
              <div class="stat-value">{{ food.portionSize || '标准' }}</div>
            </div>

            <!--<div class="stat-item">-->
            <!--<div class="stat-icon">-->
            <!--<i class="fas fa-hashtag"></i>-->
            <!--</div>-->
            <!--<div class="stat-label">产品ID</div>-->
            <!--<div class="stat-value">{{ food.id }}</div>-->
            <!--</div>-->
          </div>

          <p class="food-description">
            {{ food.description || '该菜品暂无描述信息' }}
          </p>

          <!-- 操作按钮 -->
          <div class="card-actions">
            <el-button
                type="success"
                plain
                icon="el-icon-shopping-cart"
                @click="handleAddToOrder(food)"
            >
              加入订单
            </el-button>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="foodList.length === 0 && !loading" class="empty-state">
        <i class="fas fa-utensil-spoon empty-icon"></i>
        <h3 class="empty-text">暂无餐饮产品数据</h3>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加新产品</el-button>
      </div>
    </div>

    <!-- 分页 -->
    <el-card shadow="hover" class="pagination-card">
      <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="food-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属部门ID" prop="deptId">
          <el-input v-model="form.deptId" />
        </el-form-item>
        <el-form-item label="餐饮名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="form.category" />
        </el-form-item>
        <el-form-item label="份量" prop="portionSize">
          <el-input v-model="form.portionSize" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <image-upload v-model="form.imageUrl" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listFood, getFood, delFood, addFood, updateFood } from "@/api/system/food"
import ImagePreview from '@/components/ImagePreview'
import ImageUpload from '@/components/ImageUpload'
import { addOrder } from "@/api/system/order";
export default {
  name: "FoodPage",
  components: {
    ImagePreview,
    ImageUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 餐饮产品列表
      foodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        name: null,
        price: null,
        category: null,
        portionSize: null,
        description: null,
        imageUrl: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: "所属部门ID不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "餐饮名称不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的价格格式" }
        ],
      },
      // 用于多选的食物ID数组
      selectedFoods: []
    }
  },
  created() {
    this.userId = this.$store.state.id;
    this.getList()
  },
  watch: {
    // 监听选中项变化
    selectedFoods(val) {
      this.ids = val
      this.single = val.length !== 1
      this.multiple = val.length === 0
    }
  },
  methods: {
    /** 加入订单操作 */
    handleAddToOrder(food) {
      // 从Vuex获取当前用户ID
      const userId = this.$store.state.id;

      // 构建订单对象
      const orderData = {
        userId: userId,
        productId: food.id,
        productType: "餐饮", // 固定为餐饮类型
        deptId: food.deptId,
        quantity: 1, // 默认数量为1
        unitPrice: food.price,
        totalPrice: food.price, // 总价 = 单价 * 数量
        status: "待支付" // 初始状态
      };

      // 调用API创建订单
      addOrder(orderData).then(response => {
        this.$message.success("已加入订单");
        // 可选：刷新订单数据或显示提示
        console.log(response)
      }).catch(error => {
        this.$message.error("添加失败: " + error.message);
      });
    },

    /** 检查食物是否被选中 */
    isSelected(id) {
      return this.selectedFoods.includes(id)
    },

    /** 查询餐饮产品列表 */
    getList() {
      this.loading = true
      listFood(this.queryParams).then(response => {
        this.foodList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        name: null,
        price: null,
        category: null,
        portionSize: null,
        description: null,
        imageUrl: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加餐饮产品"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getFood(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改餐饮产品"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFood(this.form).then(response => {
              console.log(response)
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addFood(this.form).then(response => {
              console.log(response)
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除餐饮产品编号为"' + ids + '"的数据项？').then(() => {
        return delFood(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
        this.selectedFoods = [] // 清空选中项
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/food/export', {
        ...this.queryParams
      }, `food_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 10px;

  .title {
    display: flex;
    align-items: center;
    gap: 12px;

    i {
      font-size: 28px;
      color: #1a9f7c;
    }

    h1 {
      font-size: 24px;
      font-weight: 700;
      color: #2d3748;
      margin: 0;
    }
  }
}

.search-card {
  border-radius: 12px;
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  .search-form {
    padding: 10px 0;

    .form-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
      gap: 16px;
      align-items: flex-end;
    }

    .form-actions {
      display: flex;
      gap: 10px;
      grid-column: span 2;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
}

.toolbar-card {
  border-radius: 12px;
  margin-bottom: 24px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  .toolbar {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    padding: 10px 0;

    .el-button {
      border-radius: 8px;
      padding: 10px 16px;
      font-weight: 500;
      transition: all 0.2s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }

    .right-toolbar {
      margin-left: auto;
    }
  }
}

.cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

.food-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.07);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: 100%;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  }
}

.card-selected {
  border: 2px solid #1a9f7c;
  box-shadow: 0 0 0 3px rgba(26, 159, 124, 0.1);
}

.card-image {
  height: 220px;
  overflow: hidden;
  position: relative;

  .food-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s ease;
  }

  &:hover .food-image {
    transform: scale(1.05);
  }
}

.card-selector {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 10;

  .selection-checkbox {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    padding: 6px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.card-content {
  padding: 20px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;

  .food-name {
    font-size: 20px;
    font-weight: 700;
    color: #2d3748;
    margin: 0;
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .food-category {
    background: #e6f7f2;
    color: #1a9f7c;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 13px;
    font-weight: 600;
    margin-left: 10px;
  }
}

.food-stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;

  .stat-icon {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: #e6f7f2;
    color: #1a9f7c;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;

    i {
      font-size: 14px;
    }
  }

  .stat-label {
    color: #718096;
    font-size: 13px;
  }

  .stat-value {
    font-weight: 500;
    color: #2d3748;
    margin-left: 4px;
  }
}

.food-description {
  color: #718096;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 20px;
  flex-grow: 1;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-actions {
  display: flex;
  gap: 12px;

  .el-button {
    flex: 1;
    border-radius: 8px;
    padding: 10px;
    font-weight: 500;
    transition: all 0.2s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
  }
}

.pagination-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  ::v-deep .el-card__body {
    display: flex;
    justify-content: center;
    padding: 16px 20px;
  }
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.07);

  .empty-icon {
    font-size: 80px;
    color: #cbd5e0;
    margin-bottom: 20px;
  }

  .empty-text {
    font-size: 18px;
    color: #718096;
    margin-bottom: 30px;
  }
}

.food-dialog {
  ::v-deep .el-dialog {
    border-radius: 16px;
    overflow: hidden;

    .el-dialog__header {
      background: #f8fafc;
      padding: 20px;
      border-bottom: 1px solid #e2e8f0;
    }

    .el-dialog__body {
      padding: 25px 30px;
    }

    .el-dialog__footer {
      padding: 15px 30px 25px;
      border-top: 1px solid #e2e8f0;
    }
  }
}

@media (max-width: 992px) {
  .cards-container {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}

@media (max-width: 768px) {
  .search-form .form-grid {
    grid-template-columns: 1fr;

    .form-actions {
      grid-column: 1;
      justify-content: center;
    }
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;

    .right-toolbar {
      margin-left: 0;
      margin-top: 10px;
    }
  }
}

@media (max-width: 576px) {
  .app-container {
    padding: 15px;
  }

  .header .title h1 {
    font-size: 20px;
  }

  .cards-container {
    grid-template-columns: 1fr;
  }
}
/* 新增按钮样式 */
.card-actions .el-button--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}
</style>
